const Koa = require("koa");
const app = new Koa();
const debug = require("debug")("koa-weapp-demo");
const cors = require("koa2-cors");
const koaBody = require("koa-body");
const path = require("path");
// 静态资源路由
const serve = require("koa-static");

const config = require("./config");

// 接收表单以及文件
app.use(
  koaBody({
    multipart: true,
    strict: true,
    formidable: {
      maxFileSize: 200 * 1024 * 1024 // 设置上传文件大小最大限制，默认2M
    }
  })
);

// 解决跨域
app.use(
  cors({
    origin: ctx => {
      console.log(ctx.request);

      if (ctx.request.header.origin === "http://localhost:8080") {
        return "http://localhost:8080";
      }
      if (ctx.request.header.origin === "http://localhost") {
        return "http://localhost";
      }
      if (ctx.request.header.origin === "http://iqiaoqi.com") {
        return "http://iqiaoqi.com";
      }
      return ["*"];
    },
    exposeHeaders: ["WWW-Authenticate", "Server-Authorization"],
    maxAge: 5,
    credentials: true,
    allowMethods: ["GET", "POST", "DELETE"],
    allowHeaders: ["Content-Type", "Authorization", "Accept"]
  })
);

// 图片放置 public 文件夹下存放
const home = serve(path.join(__dirname) + "/public/");
app.use(home);

const middlewares = require("./middlerware/response");
app.use(middlewares);

// 引入路由分发
const userRouter = require("./routes/users");
const fileRouter = require("./routes/file");

app.use(fileRouter.routes());
app.use(userRouter.routes());

app.listen(config.port, () => debug(`listening on port ${config.port}`));
